<template>
  <div class="comment-container">
    <div ref="myComment" class="comment-content">
      <div v-for="(item, index) in comments" :key="index" class="comment-item">
        <el-avatar class="avator" :size="32" :src="item.faceUrl" @error="errorHandler">
          <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png">
        </el-avatar>
        <bubble :text="item.content" />
      </div>
    </div>
  </div>
</template>

<script>
import bubble from '@/components/Bubble/index'
export default {
  components: {
    bubble
  },
  data() {
    return {
      num: 0,
      comments: [],
      hasLoadOver: false,
      pageNo: 1
    }
  },
  created() {
    this.getCommentList()
  },
  mounted() {
    this.$refs.myComment.addEventListener('scroll', this.throttle(this.scrollBottom, 1000))
  },
  methods: {
    async getCommentList() {
      const { courseId } = this.$route.query
      const params = {
        pageNo: this.pageNo,
        courseId
      }
      const res = await this.$api.getCommentList(params)
      if (res && res.code === 200) {
        if (res.data.records.length > 0) {
          this.comments.push(...res.data.records)
        } else {
          this.hasLoadOver = true
        }
      }
    },
    errorHandler() {
      return true
    },
    throttle(fn, delay) {
      let valid = true
      return () => {
        if (!valid) {
          return false
        }
        valid = false
        const timer = setTimeout(() => {
          fn()
          valid = true
          clearTimeout(timer)
        }, delay)
      }
    },
    // 触发滚动事件
    scrollBottom() {
      if (!this.hasLoadOver) {
        // 判断是否滚动到底部
        const arriveBottom = this.$refs.myComment.clientHeight + this.$refs.myComment.scrollTop - this.$refs.myComment.scrollHeight + 10
        if (arriveBottom > 0) {
          this.pageNo++
          this.getCommentList()
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.comment-content{
  position: relative;
  height: 70vh;
  width: 80%;
  margin: 0 auto;
  overflow: auto;
  border-radius: 6px;
  border: 1px solid #e7e7e7;
  box-shadow: 0 2px 10px 0 rgb(0 0 0 / 10%);
}
.comment-item{
  margin: 3px 0;
  padding: 10px 20px;
}
.avator{
  vertical-align: top;
  margin-top: 3px;
  margin-right: 10px;
}

::-webkit-scrollbar {
  width: 8px;
}
/* 滚动槽 */
::-webkit-scrollbar-track {
  box-shadow:inset006pxrgba(0,0,0,0.3);
  border-radius:10px;
}
/* 滚动条滑块 */
::-webkit-scrollbar-thumb {
  border-radius:10px;
  background:rgba(0,0,0,0.1);
  box-shadow:inset006pxrgba(0,0,0,0.5);
}
</style>
